package com.dearbinge.data.service.impl.user;

import java.math.BigDecimal;
import java.util.*;

import com.dearbinge.data.dao.*;
import com.dearbinge.data.dao.im.ImUserContactMapper;
import com.dearbinge.data.dao.userRole.UserRoleMapper;
import com.dearbinge.data.pojo.oldUser.OldUser;
import com.dearbinge.data.pojo.rocket.Rocket;
import com.dearbinge.data.pojo.shopManage.ShopManage;
import com.dearbinge.data.pojo.userWallet.UserWallet;
import com.dearbinge.utils.LocationUtils;
import com.dearbinge.utils.RandomNameUtils;
import com.dearbinge.utils.date.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.plugins.Page;
import com.dearbinge.data.api.user.UserService;
import com.dearbinge.data.pojo.user.User;
import com.dearbinge.utils.Base64Util;
import com.dearbinge.utils.PageResult;

@Transactional
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RocketMapper rocketMapper;

    @Autowired
    private OldUserMapper oldUserMapper;

    //用户角色
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private ShopManageMapper shopManageMapper;

    @Override
    public User getById(Integer id, int i) {
        User user = userMapper.getById(id);
        if (user != null && user.getName() != null) {
            user.setName(Base64Util.decodeData(user.getName()));
        }
        if (user != null && i == 0) {
            Date date = new Date();
            userMapper.updateOnLineTime(id, date);
        }
        if (user != null){
            ShopManage shopManage = shopManageMapper.getByUserId(user.getId().toString());
            if (shopManage != null){
                user.setShopId(shopManage.getId().toString());
                user.setShopName(shopManage.getShopName());
            }
        }
        return user;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public Integer insert(User user) {
        user.setName(Base64Util.encodeData(user.getName()));
        if (insertTo(user) <= 0)return 0;
        BigDecimal bigDecimal = new BigDecimal("0");
        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(user.getId().toString());
        userWallet.setFrozenMoney(bigDecimal);
        userWallet.setWalletMoney(bigDecimal);
        userWallet.setUnfrozenMoney(bigDecimal);
        userWalletMapper.insert(userWallet);
        return user.getId();
    }

    @Override
    public Integer delete(Integer id) {
        Integer dataCode = userMapper.delete(id);
        return dataCode;
    }

    @Override
    public Integer update(User user) {
        user.setName(Base64Util.encodeData(user.getName()));
        if (null != user.getRoleId()) {
            //更新用户前 先绑定用户角色id
            Integer userRoleId = user.getRoleId();
            if (userRoleId > 0) {
                user.setRoleId(userRoleId);
                userRoleMapper.update(user);
            } else {
                userRoleMapper.insert(user);
            }
            //用户角色id
            Integer userRoldId = user.getId();
            user.setRoleId(userRoldId);
        }
        Integer dataCode = userMapper.update(user);
        return dataCode;
    }

    @Override
    public User getByOpendId(String opendId) {
        User user = userMapper.getByOpendId(opendId);
        if (!StringUtils.isEmpty(user)) {
            user.setName(Base64Util.decodeData(user.getName()));
        }
        return user;
    }

    @Override
    public PageResult<List<Map<String, Object>>> getOnLineUser(Integer compositor, Integer type, String district, Integer staAge, Integer endAge, String weight, String stature, Integer emotionalState, Boolean sex, Double minLat,
                                                               Double minLng, Double maxLat, Double maxLng, Double longitude, Double latitude,
                                                               Integer pageNo, Integer pageSize) {
        String seqencing = null;
        if (compositor != null && compositor == 0){
            seqencing = "A.on_line_time";
        }else if(compositor == null){
            seqencing = "A.rank";
        }
        if (StringUtils.isEmpty(district)){
            district = null;
        }else{
            district = "%"+district+"%";
        }
        Integer count = userMapper.count(seqencing,type,district,staAge, endAge, weight, stature, emotionalState, sex, minLat, minLng, maxLat, maxLng, longitude, latitude);
        pageNo = (null == pageNo || pageNo < 1) ? 1 : pageNo;
        pageSize = (null == pageSize || pageSize < 0) ? 1 : pageSize;
        Page page = new Page(pageNo, pageSize);
        List<Map<String, Object>> mapList = userMapper.getOnLineUser(seqencing,type,district,staAge, endAge, weight, stature, emotionalState, sex, minLat, minLng, maxLat, maxLng, longitude, latitude, page);
        /**
         * 替换mapList 中的userName
         */
        if (mapList != null && mapList.size() > 0) for (Map<String, Object> mapL : mapList) {
                mapL.put("dist", null);
                if (!StringUtils.isEmpty(mapL.get("name").toString())) {
                    mapL.put("name", Base64Util.decodeData(mapL.get("name").toString()));
                }
                if (!StringUtils.isEmpty(mapL.get("longitude")) && !StringUtils.isEmpty(latitude)) {
                    Double lon = Double.parseDouble(mapL.get("longitude").toString());
                    Double lat = Double.parseDouble(mapL.get("latitude").toString());
                    if (lon != 0.0 && lat != 0.0) {
                        String distance = LocationUtils.getDistance(latitude, longitude, lat, lon);
                        mapL.put("dist", distance);
                    }
                }
            String onLineTime = DateUtils.getDistanceTime(mapL.get("onLineTime").toString(), DateUtils.date2String(new Date()), "yyyy-MM-dd HH:mm:ss");
            mapL.put("lastTime ",onLineTime);
            System.out.println("***************"+onLineTime);
            }

        if (compositor != null && compositor == 1 && mapList != null) {   //根据距离排序
            Collections.sort(mapList, new Comparator<Map<String, Object>>() {
                //降序排序
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if (StringUtils.isEmpty(o1.get("dist")) || StringUtils.isEmpty(o2.get("dist")))return mapList.size()+1;
                    double  s = Double.parseDouble(o1.get("dist").toString());
                    double  d = Double.parseDouble(o2.get("dist").toString());
                    Double D1 = new Double(s);
                    Double D2 = new Double(d);
                    Integer s1 = D1.intValue();
                    Integer s2 = D2.intValue();
                    //使用Entry类中的值来比较大小
                    return s1.compareTo(s2);
//              //使用Entry类中的键来比较大小
//                return o2.getKey().compareTo(o1.getKey());
                }
            });
        }
        Integer max = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        PageResult<List<Map<String, Object>>> pageResult = new PageResult<List<Map<String, Object>>>(mapList);
        pageResult.setTotal(Long.valueOf(count.toString()));
        pageResult.setMaxPageSize(max);
        return pageResult;
    }

    @Override
    public Integer bindingPhone(String userId, String phone) {
        Integer dataCode = userMapper.bindingPhone(userId, phone);
        if (dataCode > 0) {
            OldUser oldUser = oldUserMapper.getOldUserByMobile(phone);
            if (oldUser != null && oldUser.getO2() != null) {
                dataCode = userMapper.updateO2ByPhone(phone, oldUser.getO2());
            }
        }
        return dataCode;
    }

    @Override
    public Integer register(String userName, String pwd) {
        String name = Base64Util.encodeData(RandomNameUtils.getStringRandom(5));
        User user = new User();
        user.setByname(userName);
        user.setPwd(pwd);
        user.setName(name);
        user.setStatus(true);
        user.setHeadImg("https://uwz.blob.core.chinacloudapi.cn/quickstartcontainer/905201902211732360.png");
        Integer dataCode = insertTo(user);
        return dataCode;
    }

    private Integer insertTo(User user) {
        if (userMapper.insert(user) <= 0)return 0;
        Rocket rocket = new Rocket();
        rocket.setUserId(user.getId().toString());
        rocket.setRocketType(1);
        rocket.setRocketNumber(1);
        return rocketMapper.insert(rocket);
    }

    @Override
    public Integer checkout(String userName) {
        Integer id = userMapper.checkout(userName);
        return id;
    }

    @Override
    public Integer login(String userName, String pwd) {
        Integer dataCode = userMapper.login(userName, pwd);
        return dataCode;
    }
}
